package net.lesscoding.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author eleven
 * @date 2024/10/30 13:27
 * @apiNote
 */
public class LengthFieldDecoderTest {
    public static void main(String[] args) {
        EmbeddedChannel channel = new EmbeddedChannel(
                /**
                 * maxFrameLength 1024: 消息最大长度为1024
                 * lengthFieldOffset 0: 从头开始读取
                 * lengthFieldLength 4: 长度属性的长度 int类型为4字节
                 * lengthAdjustment 0: 长度字节后排除几个非内容字节
                 * initialBytesToStrip 4: 读取内度排除几个长度字节
                 */
                new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4),
                new LoggingHandler(LogLevel.DEBUG)
        );
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        sendMsg(buffer, "This is a test records, Has some words and symbols,you can read it in you channel buffers or log, let's try it!");
        sendMsg(buffer, "HelloWorld!");
        channel.writeInbound(buffer);
    }

    private static void sendMsg(ByteBuf buffer, String content) {
        byte[] bytes = content.getBytes();
        int length = bytes.length;
        // 先写入长度在写入内容
        buffer.writeInt(length)
                .writeBytes(bytes);
    }

}
